/**
 * @file search.c
 * Functions to manipulate a <b>Search</b> data structure.
 */

#include "search.h"

#include <stdlib.h>
#include <string.h>

Search *search_new()
{
	Search *s = (Search *)malloc(sizeof(Search));
	if(!s)
		return NULL;
	memset(s, 0, sizeof(Search));
	return s;
}

void search_delete(Search **search)
{
	free(*search);
	*search = NULL;
}

void search_clear(Search *search)
{
	if(!search)
		return;
	GList *i;
	for(i = search->result_list; i; i = i->next)
		free(i->data);
	g_list_free(search->result_list);
	search->result_list = NULL;
}

void search_set(Search *search, uint32_t req_id, const char *file_name)
{
	if(!search || !file_name)
		return;
	search->req_id = req_id;
	strncpy(search->file_name, file_name, (1<<16)-1);
	// Maybe do the check in ui.c?
}

void search_add(Search *search, const Addr *node, uint32_t file_size)
{
	if(!search || !node)
		return;
	Result *r = (Result *)malloc(sizeof(Result));
	if(!r)
		return;
	addr_cpy(&r->node, node);
	r->file_size = file_size;
	/* Check for doubles */
	GList *i;
	for(i = search->result_list; i; i = i->next) if(_result_cmp(r, i->data) == 0) {
		free(r);
		return;
	}
	/* Add the result to the list */
	search->result_list = g_list_prepend(search->result_list, r);
}

int _result_cmp(const Result *result1, const Result *result2)
{
	if(result1 == result2)
		return 0;
	if(!result1 || !result2)
		return -1;
	return (addr_cmp(&result1->node, &result2->node) == 0 &&
		result1->file_size == result2->file_size)? 0 : 1;
}
